package org.graudation.verifyCode.service.impl;

import org.graduation.model.common.ResponseResult;
import org.graduation.model.common.verifyCode.VerifyCode;
import org.graduation.utils.MyRandom;
import org.graudation.verifyCode.service.VerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {
    private final String redisKeyPrefix = "verify-code:";
    @Autowired
    private MyRandom myRandom;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private StringRedisTemplate redisTemplate;
    // 获取yml配置的发送者邮箱
    @Value("${spring.mail.username}")
    private String mainUserName;
    //发送人昵称
    @Value("${spring.mail.nickname}")
    private String nickname;

    @Override
    public ResponseResult sendCode(VerifyCode verifyCode) {
        verifyCode.setCode(myRandom.createCode());
        verifyCode.setExpired(3000);
        redisTemplate.opsForValue().set(generateRedisKey(verifyCode), verifyCode.getCode(), verifyCode.getExpired(), TimeUnit.SECONDS);
        sendMail(verifyCode);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult verifyCode(VerifyCode verifyCode) {
        String value = redisTemplate.opsForValue().get(generateRedisKey(verifyCode));
        if (verifyCode.getCode().equals(value)) {
            return ResponseResult.success();
        } else {
            return ResponseResult.failed("验证码过期或不存在");
        }
    }

    private String generateRedisKey(VerifyCode verifyCode) {
        return redisKeyPrefix + verifyCode.getServiceName() + ":" + verifyCode.getUser();
    }

    private void sendMail(VerifyCode verifyCode) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject("测试邮件");
        // 设置邮件发送者，昵称+<邮箱地址>
        message.setFrom(nickname + '<' + mainUserName + '>');
        // 设置邮件接收者，可以有多个接收者，多个接受者参数需要数组形式
        message.setTo(verifyCode.getUser());
        // 设置邮件抄送人，可以有多个抄送人
//        message.setCc("");
        // 设置隐秘抄送人，可以有多个
//        message.setBcc("");
        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        message.setText("code:" + verifyCode.getCode());
        // 发送邮件
        javaMailSender.send(message);
    }

}
